/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.cax.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * @author yk
 * @desc 用于处理Runtime.getRuntime().exec产生的错误流及输出流
 * @date 2024-06-18 17:09
 */
public class StreamGobbler extends Thread {
    InputStream is;
    String type;
    OutputStream os;
    String logUrl;


    StreamGobbler(InputStream is, String type, String logUrl) {
        this(is, type, null, logUrl);
    }

    StreamGobbler(InputStream is, String type, OutputStream redirect, String logUrl) {
        this.is = is;
        this.type = type;
        this.os = redirect;
        this.logUrl = logUrl;
    }

    @Override
    public void run() {
        InputStreamReader isr = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {

            isr = new InputStreamReader(is, "GBK");
            br = new BufferedReader(isr);
            String line = null;
            File file = new File(logUrl);
            file.createNewFile();
            bw = new BufferedWriter(new FileWriter(file));
            while ((line = br.readLine()) != null) {
                if (bw != null) {
                    bw.write(line + "\n");
                }
            }

            if (bw != null) {
                bw.flush();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
